package controllers

import (
	"document/models"
	"encoding/json"
	beego "github.com/beego/beego/v2/server/web"
	"strconv"
	"time"
)

type DocumentController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *DocumentController) List() {
	page, _ := c.GetInt("page")
	size, _ := c.GetInt("size")
	key := "documen-" + strconv.Itoa(page)
	val, err := models.Rdb.Get(key).Result()
	pageData := make(map[string]interface{})
	if err != nil {
		var count int64
		err = models.DB.Model(&models.Document{}).Count(&count).Error
		if err != nil {
			c.Data["jsn"] = JsonR{
				Code: 500,
				Msg:  "总数据展示失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		}
		Offset := (page - 1) * size
		var document models.Document
		err = models.DB.Offset(Offset).Limit(size).Find(&document).Error
		pageData["count"] = count
		pageData["document"] = document
		if err != nil {
			c.Data["json"] = JsonR{
				Code: 500,
				Msg:  "数据查询失败",
				Data: nil,
			}
			c.ServeJSON()
			return
		} else {
			marshal, _ := json.Marshal(pageData)
			values := string(marshal)
			models.Rdb.Set(key, values, time.Second*10)
			c.Data["json"] = JsonR{
				Code: 200,
				Msg:  "mysql查询成功",
				Data: pageData,
			}
			c.ServeJSON()
		}
	} else {
		json.Unmarshal([]byte(val), pageData)
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "redis查询成功",
			Data: pageData,
		}
		c.ServeJSON()
	}
}
